package eg.edu.eelu.fyp2013.jdetector.gui;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import java.awt.GridLayout;
import java.awt.Image;
import java.awt.image.BufferedImage;

import javax.swing.Icon;

import matlabcontrol.MatlabConnectionException;
import matlabcontrol.MatlabInvocationException;
import matlabcontrol.MatlabProxy;
import matlabcontrol.MatlabProxyFactory;
import matlabcontrol.extensions.MatlabNumericArray;
import matlabcontrol.extensions.MatlabTypeConverter;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JSplitPane;
import javax.swing.JInternalFrame;
import javax.swing.JSeparator;
import javax.swing.SwingConstants;
import javax.swing.JDesktopPane;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.TitledBorder;
import javax.swing.UIManager;

import java.awt.FlowLayout;

import javax.swing.BoxLayout;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.border.LineBorder;

import java.awt.Color;

import javax.swing.border.SoftBevelBorder;
import javax.swing.border.BevelBorder;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextPane;

import java.awt.Font;

import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;

import java.awt.Window.Type;
import java.awt.Button;

import javax.swing.JProgressBar;

import eg.edu.eelu.fyp2013.jdetector.core.Enhancement.Enhance;
import eg.edu.eelu.fyp2013.jdetector.core.classifier.KLDAPlusEuclidanDist;
import eg.edu.eelu.fyp2013.jdetector.core.classifier.NerualNetworkClassifier;
import eg.edu.eelu.fyp2013.jdetector.core.input_output.AMatrix;
import eg.edu.eelu.fyp2013.jdetector.core.input_output.ClassiferData;
import eg.edu.eelu.fyp2013.jdetector.core.input_output.FeatureExtraction;
import eg.edu.eelu.fyp2013.jdetector.core.input_output.LoadData;
import eg.edu.eelu.fyp2013.jdetector.core.swt.KLDANeuralPCA;
import eg.edu.eelu.fyp2013.jdetector.core.swt.ReducePCANeural;
import eg.edu.eelu.fyp2013.jdetector.core.swt.ReductionDeminsion_PCA;
import eg.edu.eelu.fyp2013.jdetector.core.swt.swtFExtraction;

import java.awt.Component;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.util.ArrayList;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Proxy;

import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import com.mathworks.toolbox.javabuilder.MWException;

public class MRI_Brain_Tumor_Classification_Tool extends JFrame {
	
	private BufferedImage SamplePreviewImage;

	private JPanel contentPane;

	int learnnormal = 0;
	int learnabnormal = 0;
	int testnormal = 0;
	int testabnormal = 0;
	
	/**
	 * Launch the application.
	 */
	AMatrix DataMatrix;
	ArrayList<AMatrix> TestDataMatixList = new ArrayList<AMatrix>();
	ArrayList<AMatrix> LearnDataMatixList = new ArrayList<AMatrix>();
	ArrayList<AMatrix> learnMedMatixList = new ArrayList<AMatrix>();

	ArrayList<AMatrix> testMedMatixList = new ArrayList<AMatrix>();
	
	ArrayList<FeatureExtraction> learnFeaturedMatixList = new ArrayList<FeatureExtraction>();
	ArrayList<FeatureExtraction> testFeaturedMatixList = new ArrayList<FeatureExtraction>();

	ArrayList<ArrayList<FeatureExtraction>> levellearnFeaturedMatixList = new ArrayList<ArrayList<FeatureExtraction>>();
	ArrayList<ArrayList<FeatureExtraction>> leveltestFeaturedMatixList = new ArrayList<ArrayList<FeatureExtraction>>();
	
	private JTextField learnTextField;
	private JTextField testTextField;
	
	ClassiferData [] Finallearnfeatures;
	ClassiferData [] Finaltextfeatures;
	
	ClassiferData [] FinalNeurallearnfeatures;
	ClassiferData [] FinalNerualtextfeatures;
	
	
	ClassiferData [] learndata;
	ClassiferData [] testdata;
	private JTable StatisticsTable;
	private JTable DataTabel;
	
	public static void main(String[] args) throws MatlabConnectionException{
		
	
		
		
		////
		try {
            // Set System L&F
        UIManager.setLookAndFeel(
            UIManager.getSystemLookAndFeelClassName());
    } 
    catch (UnsupportedLookAndFeelException e) {
       // handle exception
    }
    catch (ClassNotFoundException e) {
       // handle exception
    }
    catch (InstantiationException e) {
       // handle exception
    }
    catch (IllegalAccessException e) {
       // handle exception
    }

 //   new SwingApplication(); //Create and show the GUI.
		
		////
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MRI_Brain_Tumor_Classification_Tool frame = new MRI_Brain_Tumor_Classification_Tool();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 * @throws MatlabConnectionException 
	 */
	public MRI_Brain_Tumor_Classification_Tool()  {
		

		
		
		 
		
		
		setResizable(false);
		setTitle("JDetector (MRI Classification Learning Tool)");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(300, 10, 700, 700);
		
		contentPane = new JPanel();
		contentPane.setToolTipText("");
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new GridLayout(1, 0, 0, 0));
		
		JPanel panel = new JPanel();
		panel.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		contentPane.add(panel);
		
		final JPanel SamplePreviewPanel = new JPanel();
		SamplePreviewPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Sample Viewer", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		
		JPanel ResultPreviewpanel = new JPanel();
		ResultPreviewpanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Result Viewer", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		
		JLabel lblBrainTumor = new JLabel("--== Brain Tumor Magnetic Resonance Imaging Classification ==--");
		lblBrainTumor.setFont(new Font("Tahoma", Font.BOLD, 13));
		lblBrainTumor.setHorizontalAlignment(SwingConstants.CENTER);
		
		JPanel LearnPreviewpanel = new JPanel();
		LearnPreviewpanel.setBorder(new TitledBorder(null, "Data", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		
		JPanel panel_6 = new JPanel();
		panel_6.setBorder(new TitledBorder(null, "Results", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		
		JPanel panel_7 = new JPanel();
		panel_7.setBorder(new TitledBorder(null, "Classification", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		
		JPanel panel_10 = new JPanel();
		panel_10.setBorder(new TitledBorder(null, "Feature Extraction and Data Reduction", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		GroupLayout gl_panel = new GroupLayout(panel);
		gl_panel.setHorizontalGroup(
			gl_panel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel.createSequentialGroup()
					.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_panel.createSequentialGroup()
							.addContainerGap()
							.addComponent(panel_6, GroupLayout.DEFAULT_SIZE, 661, Short.MAX_VALUE))
						.addGroup(gl_panel.createSequentialGroup()
							.addGap(91)
							.addComponent(lblBrainTumor))
						.addGroup(gl_panel.createSequentialGroup()
							.addContainerGap()
							.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_panel.createSequentialGroup()
									.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
										.addComponent(panel_10, GroupLayout.PREFERRED_SIZE, 386, GroupLayout.PREFERRED_SIZE)
										.addComponent(panel_7, GroupLayout.PREFERRED_SIZE, 380, GroupLayout.PREFERRED_SIZE))
									.addGap(18)
									.addComponent(ResultPreviewpanel, GroupLayout.PREFERRED_SIZE, 260, GroupLayout.PREFERRED_SIZE))
								.addGroup(gl_panel.createSequentialGroup()
									.addComponent(LearnPreviewpanel, GroupLayout.PREFERRED_SIZE, 389, GroupLayout.PREFERRED_SIZE)
									.addPreferredGap(ComponentPlacement.UNRELATED)
									.addComponent(SamplePreviewPanel, GroupLayout.PREFERRED_SIZE, 260, GroupLayout.PREFERRED_SIZE)))
							.addGap(6)))
					.addContainerGap())
		);
		gl_panel.setVerticalGroup(
			gl_panel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel.createSequentialGroup()
					.addContainerGap()
					.addComponent(lblBrainTumor)
					.addGap(13)
					.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
						.addComponent(LearnPreviewpanel, GroupLayout.PREFERRED_SIZE, 256, GroupLayout.PREFERRED_SIZE)
						.addComponent(SamplePreviewPanel, GroupLayout.PREFERRED_SIZE, 260, GroupLayout.PREFERRED_SIZE))
					.addGroup(gl_panel.createParallelGroup(Alignment.TRAILING)
						.addGroup(gl_panel.createSequentialGroup()
							.addGap(7)
							.addComponent(panel_10, GroupLayout.PREFERRED_SIZE, 99, GroupLayout.PREFERRED_SIZE)
							.addGap(4)
							.addComponent(panel_7, 0, 0, Short.MAX_VALUE))
						.addGroup(gl_panel.createSequentialGroup()
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(ResultPreviewpanel, GroupLayout.PREFERRED_SIZE, 260, GroupLayout.PREFERRED_SIZE)))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(panel_6, GroupLayout.PREFERRED_SIZE, 80, GroupLayout.PREFERRED_SIZE)
					.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
		);
		
		StatisticsTable = new JTable();
		StatisticsTable.setModel(new DefaultTableModel(
			new Object[][] {
				{"Classify Technique", "TP", "TN", "FP", "FN", "Sensitivity", "Specificity", "Accuracy "},
				{"SWT+PCA/KLDA+ANN", 0, 0, 0, 0, 0, 0, 0},
				{"SWT+PCA/KLDA+ED", 0, 0, 0, 0, 0, 0, 0},
			},
			new String[] {
				"Classification Type", " TP", "TN", "FP", "FN", "Sen", "Specif", "Acc"
			}
		));
		StatisticsTable.getColumnModel().getColumn(0).setPreferredWidth(130);
		StatisticsTable.getColumnModel().getColumn(1).setPreferredWidth(29);
		StatisticsTable.getColumnModel().getColumn(2).setPreferredWidth(26);
		StatisticsTable.getColumnModel().getColumn(3).setPreferredWidth(28);
		StatisticsTable.getColumnModel().getColumn(4).setPreferredWidth(29);
		StatisticsTable.getColumnModel().getColumn(5).setPreferredWidth(64);
		StatisticsTable.getColumnModel().getColumn(6).setPreferredWidth(65);
		StatisticsTable.getColumnModel().getColumn(7).setPreferredWidth(62);
		StatisticsTable.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
		
		DataTabel = new JTable();
		DataTabel.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
		DataTabel.setModel(new DefaultTableModel(
			new Object[][] {
				{"Data", "Normal ", "Abnormal"},
				{"Learned", "0", "0"},
				{"Tested", "0", "0"},
			},
			new String[] {
				"New column", "Nor", "AbNor"
			}
		));
		DataTabel.getColumnModel().getColumn(0).setPreferredWidth(55);
		DataTabel.getColumnModel().getColumn(1).setPreferredWidth(51);
		DataTabel.getColumnModel().getColumn(2).setPreferredWidth(62);
		GroupLayout gl_panel_6 = new GroupLayout(panel_6);
		gl_panel_6.setHorizontalGroup(
			gl_panel_6.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_panel_6.createSequentialGroup()
					.addContainerGap()
					.addComponent(DataTabel, GroupLayout.DEFAULT_SIZE, 189, Short.MAX_VALUE)
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addComponent(StatisticsTable, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
					.addContainerGap())
		);
		gl_panel_6.setVerticalGroup(
			gl_panel_6.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_6.createSequentialGroup()
					.addGroup(gl_panel_6.createParallelGroup(Alignment.BASELINE)
						.addComponent(DataTabel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(StatisticsTable, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
		);
		panel_6.setLayout(gl_panel_6);
		ResultPreviewpanel.setLayout(new GridLayout(1, 0, 0, 0));
		
		final JLabel ResultPreviewLabel = new JLabel("");
		ResultPreviewpanel.add(ResultPreviewLabel);
		SamplePreviewPanel.setLayout(new GridLayout(0, 1, 0, 0));
		
		final JLabel PreviewLabel = new JLabel("");
		PreviewLabel.setVerticalAlignment(SwingConstants.TOP);
		PreviewLabel.setHorizontalAlignment(SwingConstants.LEFT);
		SamplePreviewPanel.add(PreviewLabel);
		final JProgressBar SWTprogressBar = new JProgressBar();
		JPanel panel_11 = new JPanel();
		final JComboBox swtLevels = new JComboBox();
		swtLevels.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3", "4", "5"}));
		swtLevels.setSelectedIndex(2);
		
		JButton btnSwt = new JButton("SWT");
		btnSwt.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
							
					swtFExtraction S = new swtFExtraction();
					int x = swtLevels.getSelectedIndex();
					for(int i = 0; i <=  x; i++){
					   
					    	
					    	
					    	if(learnMedMatixList.size() > 0)
					    	{
							   learnFeaturedMatixList =  S.swtExtract(i+1,learnMedMatixList);
							   if( i == swtLevels.getSelectedIndex() )
							   {
								   ResultPreviewLabel.setIcon(new ImageIcon(learnFeaturedMatixList.get(learnFeaturedMatixList.size() - 1).extractImagedecli));
								   
							   }
							   
							   levellearnFeaturedMatixList.add(learnFeaturedMatixList);
							   
					    	}
					        if(testMedMatixList.size() > 0)
					    	{
							    testFeaturedMatixList =  S.swtExtract(i+1,testMedMatixList); 
							    
							    if( i == swtLevels.getSelectedIndex() )
								   {
							 	   ResultPreviewLabel.setIcon(new ImageIcon(testFeaturedMatixList.get(testFeaturedMatixList.size() - 1 ).extractImagedecli));
							    	   
								   }
								leveltestFeaturedMatixList.add(testFeaturedMatixList);   
							 
					    	}
					        
					        int size1 = levellearnFeaturedMatixList.size();
					        System.out.print(size1);
					        int size2 = leveltestFeaturedMatixList.size();
					        System.out.print(size2);
					        
					        SWTprogressBar.setValue(50);
					        
							
					}	
				
					String st="Feature Extraction Done!";
					JOptionPane.showMessageDialog(null,st);
			}
		});
	
				
		JButton btnPca = new JButton("PCA + KLDA");
		btnPca.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				ReductionDeminsion_PCA RDP = new ReductionDeminsion_PCA();
				ReducePCANeural NNP = new ReducePCANeural();
				
				int x = swtLevels.getSelectedIndex();
				
			          for(int i = 0 ; i < levellearnFeaturedMatixList.size(); i++)
			          {
			        	  if(levellearnFeaturedMatixList.get(i) == null)
			        	  {
			        		  levellearnFeaturedMatixList.remove(i);
			        	  }
			          }
			          for(int i = 0 ; i < leveltestFeaturedMatixList.size(); i++)
			          {
			        	  if(leveltestFeaturedMatixList.get(i) == null)
			        	  {
			        		  leveltestFeaturedMatixList.remove(i);
			        	  }
			          }
					    
						
							if(levellearnFeaturedMatixList.size() > 0)
							{
								
							   try {
								Finallearnfeatures = RDP.reducefeatures(levellearnFeaturedMatixList, x);
								FinalNeurallearnfeatures = NNP.reducefeatures(levellearnFeaturedMatixList, x);
							} catch (MWException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
							   
							}
							if (leveltestFeaturedMatixList.size() > 0)
							{
							   try {
								Finaltextfeatures  = RDP.reducefeatures(leveltestFeaturedMatixList, x);
								FinalNerualtextfeatures = NNP.reducefeatures(leveltestFeaturedMatixList, x);
							} catch (MWException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
							  
							}
					
							String st="PCA + KLDA Done!";
							SWTprogressBar.setValue(100);
							JOptionPane.showMessageDialog(null,st);
							 
						
			}
		});
		
		
		GroupLayout gl_panel_10 = new GroupLayout(panel_10);
		gl_panel_10.setHorizontalGroup(
			gl_panel_10.createParallelGroup(Alignment.LEADING)
				.addComponent(panel_11, GroupLayout.PREFERRED_SIZE, 368, Short.MAX_VALUE)
		);
		gl_panel_10.setVerticalGroup(
			gl_panel_10.createParallelGroup(Alignment.TRAILING)
				.addGroup(Alignment.LEADING, gl_panel_10.createSequentialGroup()
					.addContainerGap()
					.addComponent(panel_11, GroupLayout.PREFERRED_SIZE, 61, GroupLayout.PREFERRED_SIZE)
					.addContainerGap())
		);
		GroupLayout gl_panel_11 = new GroupLayout(panel_11);
		gl_panel_11.setHorizontalGroup(
			gl_panel_11.createParallelGroup(Alignment.LEADING)
				.addGroup(Alignment.TRAILING, gl_panel_11.createSequentialGroup()
					.addGap(0, 0, Short.MAX_VALUE)
					.addGroup(gl_panel_11.createParallelGroup(Alignment.LEADING)
						.addComponent(SWTprogressBar, GroupLayout.PREFERRED_SIZE, 348, GroupLayout.PREFERRED_SIZE)
						.addGroup(gl_panel_11.createParallelGroup(Alignment.LEADING, false)
							.addGroup(gl_panel_11.createSequentialGroup()
								.addComponent(btnSwt, GroupLayout.PREFERRED_SIZE, 174, GroupLayout.PREFERRED_SIZE)
								.addComponent(swtLevels, GroupLayout.PREFERRED_SIZE, 174, GroupLayout.PREFERRED_SIZE))
							.addComponent(btnPca, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
					.addGap(20))
		);
		gl_panel_11.setVerticalGroup(
			gl_panel_11.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_11.createSequentialGroup()
					.addGroup(gl_panel_11.createParallelGroup(Alignment.LEADING)
						.addComponent(btnSwt, GroupLayout.PREFERRED_SIZE, 19, GroupLayout.PREFERRED_SIZE)
						.addComponent(swtLevels, GroupLayout.PREFERRED_SIZE, 19, GroupLayout.PREFERRED_SIZE))
					.addGap(2)
					.addComponent(btnPca, GroupLayout.PREFERRED_SIZE, 19, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
					.addComponent(SWTprogressBar, GroupLayout.PREFERRED_SIZE, 15, GroupLayout.PREFERRED_SIZE))
		);
		panel_11.setLayout(gl_panel_11);
		panel_10.setLayout(gl_panel_10);
		
		JPanel panel_4 = new JPanel();
		panel_4.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Neural Network", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		
		JPanel panel_8 = new JPanel();
		panel_8.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), " ", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		GroupLayout gl_panel_4 = new GroupLayout(panel_4);
		gl_panel_4.setHorizontalGroup(
			gl_panel_4.createParallelGroup(Alignment.TRAILING)
				.addGroup(Alignment.LEADING, gl_panel_4.createSequentialGroup()
					.addContainerGap()
					.addComponent(panel_8, GroupLayout.DEFAULT_SIZE, 134, Short.MAX_VALUE)
					.addContainerGap())
		);
		gl_panel_4.setVerticalGroup(
			gl_panel_4.createParallelGroup(Alignment.LEADING)
				.addComponent(panel_8, GroupLayout.PREFERRED_SIZE, 98, Short.MAX_VALUE)
		);
		panel_8.setLayout(new GridLayout(0, 1, 0, 0));
		final JProgressBar neuralProgressBar = new JProgressBar();

		JButton btnTrain = new JButton("Train");
		btnTrain.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				
				
					
					
					KLDANeuralPCA Kll = new KLDANeuralPCA();
							
				    try {
						Kll.classifykernalplusdistance(FinalNeurallearnfeatures, FinalNerualtextfeatures);
					} catch (MWException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				 
				    
			     	learndata  = Kll.getlearnedred();
				    testdata = Kll.gttestedred();
					
				
			    
			   
          
				/*		KLDANeuralPCA Kll = new KLDANeuralPCA();
						try {
							Kll.classifykernalplusdistance(FinalNeurallearnfeatures, FinalNerualtextfeatures, proxy , factory , processor );
						} catch (MWException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}*/
					//	learndata  = Kll.getlearnedred();
					   // testdata = Kll.gttestedred();
						

				NerualNetworkClassifier n = new NerualNetworkClassifier();
				n.multiNNBuild(learndata);
				
				
			
				
				 
				System.out.println("Trained");
				String st="Training Done!";
				JOptionPane.showMessageDialog(null,st);
				neuralProgressBar.setValue(50);
				
			}
		});
		panel_8.add(btnTrain);
		
		JButton btnClassify = new JButton("Test");
		btnClassify.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// just to test the text area to be removed later
				//textArea.setText("test test");
				NerualNetworkClassifier t = new NerualNetworkClassifier();
				String [] testResult;
				testResult= t.multiNNTest(testdata);
				double [] fulloutput = new double [testResult.length];  
				for(int i = 0 ; i < testResult.length; i++)
				{
					
					fulloutput[i] = Double.parseDouble((testResult[i].substring(1, testResult[i].length()-1)));
				}
				
				
				double [] ALLStat = t.showdataintable(fulloutput);
				
		
				StatisticsTable.setValueAt(ALLStat[0], 1, 1); 
				StatisticsTable.setValueAt(ALLStat[1], 1, 2); 
				StatisticsTable.setValueAt(ALLStat[2], 1, 3); 
				StatisticsTable.setValueAt(ALLStat[3], 1, 4); 
				StatisticsTable.setValueAt(ALLStat[4], 1, 5); 
				StatisticsTable.setValueAt(ALLStat[5], 1, 6);
				StatisticsTable.setValueAt(ALLStat[6], 1, 7); 
				
				// we can either get the input from the feature extraction or easier to get the input from the test function 
				//textArea.setText(testResult);
				//for(int i = 0 ; i < testResult.length; i++){
				//textArea.append(testResult[i] + "\n");}
						
				neuralProgressBar.setValue(100);
			}
		});
		panel_8.add(btnClassify);
		
		panel_8.add(neuralProgressBar);
		
		JButton SaveANNBtn = new JButton("Save");
		SaveANNBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				NerualNetworkClassifier KD = new NerualNetworkClassifier();
				  
				try {
					KD.Savelearnedfeaturesandlabel(FinalNeurallearnfeatures);
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
			}
		});
		panel_8.add(SaveANNBtn);
		panel_4.setLayout(gl_panel_4);
		
		JPanel panel_5 = new JPanel();
		panel_5.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Eucladian distance", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		
		JPanel panel_9 = new JPanel();
		GroupLayout gl_panel_5 = new GroupLayout(panel_5);
		gl_panel_5.setHorizontalGroup(
			gl_panel_5.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_5.createSequentialGroup()
					.addContainerGap()
					.addComponent(panel_9, GroupLayout.PREFERRED_SIZE, 125, Short.MAX_VALUE)
					.addContainerGap())
		);
		gl_panel_5.setVerticalGroup(
			gl_panel_5.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_5.createSequentialGroup()
					.addGap(5)
					.addComponent(panel_9, GroupLayout.PREFERRED_SIZE, 71, GroupLayout.PREFERRED_SIZE)
					.addContainerGap(22, Short.MAX_VALUE))
		);
		final JProgressBar EDprogressBar = new JProgressBar();
		JButton EDistanceClassifyBtn = new JButton("Classify");
		EDistanceClassifyBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				
						
						KLDAPlusEuclidanDist KD = new KLDAPlusEuclidanDist();
					    try {
							double [] ALLStat = KD.classifykernalplusdistance(Finallearnfeatures, Finaltextfeatures);
							StatisticsTable.setValueAt(ALLStat[0], 2, 1); 
							StatisticsTable.setValueAt(ALLStat[1], 2, 2); 
							StatisticsTable.setValueAt(ALLStat[2], 2, 3); 
							StatisticsTable.setValueAt(ALLStat[3], 2, 4); 
							StatisticsTable.setValueAt(ALLStat[4], 2, 5); 
							StatisticsTable.setValueAt(ALLStat[5], 2, 6);
							StatisticsTable.setValueAt(ALLStat[6], 2, 7); 
							
						} catch (MWException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
						
						String st="ED Classification Done!";
						JOptionPane.showMessageDialog(null,st);
						EDprogressBar.setValue(100);
					
				
			}
		});
		panel_9.setLayout(new GridLayout(0, 1, 0, 3));
		panel_9.add(EDistanceClassifyBtn);
		

		panel_9.add(EDprogressBar);
		
		JButton SaveEDistncBtn = new JButton("Save");
		SaveEDistncBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				KLDAPlusEuclidanDist KD = new KLDAPlusEuclidanDist();
			  
				try {
					KD.Savelearnedfeaturesandlabel(Finallearnfeatures);
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
			}
		});
		panel_9.add(SaveEDistncBtn);
		panel_5.setLayout(gl_panel_5);
		GroupLayout gl_panel_7 = new GroupLayout(panel_7);
		gl_panel_7.setHorizontalGroup(
			gl_panel_7.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_7.createSequentialGroup()
					.addContainerGap()
					.addComponent(panel_4, GroupLayout.PREFERRED_SIZE, 170, GroupLayout.PREFERRED_SIZE)
					.addGap(18)
					.addComponent(panel_5, GroupLayout.PREFERRED_SIZE, 156, GroupLayout.PREFERRED_SIZE)
					.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
		);
		gl_panel_7.setVerticalGroup(
			gl_panel_7.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_7.createSequentialGroup()
					.addGroup(gl_panel_7.createParallelGroup(Alignment.BASELINE)
						.addComponent(panel_4, GroupLayout.PREFERRED_SIZE, 123, GroupLayout.PREFERRED_SIZE)
						.addComponent(panel_5, GroupLayout.PREFERRED_SIZE, 123, GroupLayout.PREFERRED_SIZE))
					.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
		);
		panel_7.setLayout(gl_panel_7);
		

		
		
		JButton btnNewButton = new JButton("-");
		btnNewButton.addActionListener(new ActionListener() {
			JFileChooser j = new JFileChooser();
			public void actionPerformed(ActionEvent e) {
				j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				//j.setAcceptAllFileFilterUsed(false);
				//Integer opt = 
				j.showDialog(learnTextField, "Open");
				learnTextField.setText(j.getSelectedFile().toString());
				
			}
		});
		
		JLabel learnDataPathLabel = new JLabel("Learning Data Path");
		
		final JComboBox learninComboBox = new JComboBox();
		learninComboBox.setModel(new DefaultComboBoxModel(new String[] {"Normal", "Abnormal"}));
		
		JButton LearningDataLoadButton =  new JButton("Load");
		LearningDataLoadButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				LoadData ld = new LoadData();
				AMatrix[] LearnnormalDataMatrix = null;
				AMatrix[] learnabnormalDataMatrix = null;
				
				
				if (learninComboBox.getSelectedIndex()== 0)
				{
					LearnnormalDataMatrix = ld.loadabNormallearningdata(learnTextField.getText(), 0);
					learnnormal = learnnormal + LearnnormalDataMatrix.length;
					DataTabel.setValueAt(learnnormal, 1, 1);
					for(int i = 0 ; i < LearnnormalDataMatrix.length; i++){
						
						//PreviewLabel.setIcon(new ImageIcon());

						LearnDataMatixList.add(LearnnormalDataMatrix[i]);
						
						PreviewLabel.setIcon(new ImageIcon(LearnnormalDataMatrix[i].GetImage));
						    //main.setContentPane(panel2);
						  //setContentPane(SamplePreviewPanel);
						// validate();
						// repaint();
						  
							
						
						//PreviewLabel.update(null);
					/*	try {
							SamplePreviewImage = ImageIO.read(new File(ld.imageFileName));
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}*/
					}
				}
				else
				{
					learnabnormalDataMatrix = ld.loadabNormallearningdata(learnTextField.getText(), 1);
					learnabnormal = learnabnormal + learnabnormalDataMatrix.length;
					DataTabel.setValueAt(learnabnormal, 1, 2);
					for(int i = 0 ; i < learnabnormalDataMatrix.length; i++){
						LearnDataMatixList.add(learnabnormalDataMatrix[i]);
						 PreviewLabel.setIcon(new ImageIcon(learnabnormalDataMatrix[i].GetImage));
/*						try {
							SamplePreviewImage = ImageIO.read(new File(ld.imageFileName));
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}*/
					}
				}
				
				int s = LearnDataMatixList.size();
				System.out.println(s);
				System.out.println();
				
				 
				
				// view result
				//PreviewLabel.setIcon(new ImageIcon(SamplePreviewImage));
				
			}
		});
		
		JButton learnImageInhancmentButton = new JButton("Learning Image Enhancement");
		learnImageInhancmentButton.addActionListener(new ActionListener() {
			
			public void actionPerformed(ActionEvent e) {
				Enhance E = new Enhance();
				
				ArrayList<AMatrix> MedDataMatrixlist  = E.ApplyEnhance(LearnDataMatixList);
				
				for(int i = 0 ; i < MedDataMatrixlist.size() ; i++)
				{
					learnMedMatixList.add(MedDataMatrixlist.get(i));
					ResultPreviewLabel.setIcon(new ImageIcon(MedDataMatrixlist.get(i).GetImage));
					
					
				}
				
				int s3 = learnMedMatixList.size();
				System.out.print(s3);
			}
		});
		
		JButton button = new JButton("-");
		button.addActionListener(new ActionListener() {
			JFileChooser j = new JFileChooser();
			public void actionPerformed(ActionEvent e) {
				j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				//j.setAcceptAllFileFilterUsed(false);
				//Integer opt = 
				j.showDialog(learnTextField, "Open");
				testTextField.setText(j.getSelectedFile().toString());
			}
		});
		
		JLabel lblTestingDataPath = new JLabel("Testing Data Path");
		
		final JComboBox testComboBox = new JComboBox();
		testComboBox.setModel(new DefaultComboBoxModel(new String[] {"Normal", "Abnormal"}));
		
		JButton TestingDataLoadButton = new JButton("Load");
		TestingDataLoadButton.addActionListener(new ActionListener() {
			
			public void actionPerformed(ActionEvent e) {
				LoadData ld = new LoadData();
				AMatrix[] TestnormalDataMatrix = null;
				AMatrix[] TestabnormalDataMatrix = null ;

				if (testComboBox.getSelectedIndex()== 0)
				{
					TestnormalDataMatrix = ld.loadabNormallearningdata(testTextField.getText(), 0);
					testnormal = testnormal + TestnormalDataMatrix.length;
					DataTabel.setValueAt(testnormal, 2, 1);
					for(int i = 0 ; i < TestnormalDataMatrix.length; i++){
				
						TestDataMatixList.add(TestnormalDataMatrix[i]);
						 PreviewLabel.setIcon(new ImageIcon(TestnormalDataMatrix[i].GetImage));
					}
				}
				else
				{
					TestabnormalDataMatrix = ld.loadabNormallearningdata(testTextField.getText(), 1);
					testabnormal = testabnormal + TestabnormalDataMatrix.length;
					DataTabel.setValueAt(testabnormal, 2, 2);
					for(int i = 0 ; i < TestabnormalDataMatrix.length; i++){
						TestDataMatixList.add(TestabnormalDataMatrix[i]);
						 PreviewLabel.setIcon(new ImageIcon(TestabnormalDataMatrix[i].GetImage));
				       }
				}
					
				
			int s2 = TestDataMatixList.size();
			System.out.print(s2);
		}
	});
		
		JButton btnTestingImageEnhancement = new JButton("Testing Image Enhancement");
		btnTestingImageEnhancement.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Enhance E = new Enhance();
				
				ArrayList<AMatrix> MedDataMatrixlist  = E.ApplyEnhance(TestDataMatixList);
				
				for(int i = 0 ; i < MedDataMatrixlist.size() ; i++)
				{
					testMedMatixList.add(MedDataMatrixlist.get(i));
					ResultPreviewLabel.setIcon(new ImageIcon(MedDataMatrixlist.get(i).GetImage));
					
				}
				int s4 = testMedMatixList.size();
				System.out.print(s4);
			}
			
		});
		
		learnTextField = new JTextField();
		learnTextField.setText("C:\\JDetector\\Learning Normal");
		learnTextField.setColumns(10);
		
		testTextField = new JTextField();
		testTextField.setText("C:\\JDetector\\Learning Normal");
		testTextField.setColumns(10);
		
		JButton clearLearn = new JButton("Clear");
		clearLearn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				
				learnabnormal = 0;
				learnnormal = 0;
				DataTabel.setValueAt(learnnormal, 1, 1);
				DataTabel.setValueAt(learnabnormal, 1, 2);
				LearnDataMatixList.clear();
			    PreviewLabel.setIcon(null);
			    learnMedMatixList.clear();
				ResultPreviewLabel.setIcon(null);
						
			}
			
			
			
		});
		
		JButton ClearTest = new JButton("Clear");
		ClearTest.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				
				testnormal = 0;
				testabnormal = 0;
				DataTabel.setValueAt(testnormal, 2, 1);
				DataTabel.setValueAt(testabnormal, 2, 2);
				TestDataMatixList.clear();
				PreviewLabel.setIcon(null);
				testMedMatixList.clear();
				ResultPreviewLabel.setIcon(null);
			}
		});
		GroupLayout gl_panel_3 = new GroupLayout(LearnPreviewpanel);
		gl_panel_3.setHorizontalGroup(
			gl_panel_3.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_3.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_panel_3.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_panel_3.createSequentialGroup()
							.addGroup(gl_panel_3.createParallelGroup(Alignment.LEADING, false)
								.addGroup(gl_panel_3.createSequentialGroup()
									.addGroup(gl_panel_3.createParallelGroup(Alignment.LEADING)
										.addComponent(learnDataPathLabel)
										.addComponent(LearningDataLoadButton, GroupLayout.PREFERRED_SIZE, 113, GroupLayout.PREFERRED_SIZE))
									.addPreferredGap(ComponentPlacement.RELATED)
									.addGroup(gl_panel_3.createParallelGroup(Alignment.LEADING)
										.addGroup(gl_panel_3.createSequentialGroup()
											.addComponent(learnTextField, GroupLayout.PREFERRED_SIZE, 150, GroupLayout.PREFERRED_SIZE)
											.addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
											.addComponent(btnNewButton, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE))
										.addGroup(Alignment.TRAILING, gl_panel_3.createSequentialGroup()
											.addComponent(learninComboBox, 0, 100, Short.MAX_VALUE)
											.addPreferredGap(ComponentPlacement.UNRELATED)
											.addComponent(clearLearn, GroupLayout.PREFERRED_SIZE, 88, GroupLayout.PREFERRED_SIZE))))
								.addGroup(Alignment.TRAILING, gl_panel_3.createParallelGroup(Alignment.TRAILING)
									.addComponent(learnImageInhancmentButton, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 306, Short.MAX_VALUE)
									.addGroup(gl_panel_3.createSequentialGroup()
										.addComponent(lblTestingDataPath, GroupLayout.PREFERRED_SIZE, 108, GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(ComponentPlacement.UNRELATED)
										.addComponent(testTextField, GroupLayout.PREFERRED_SIZE, 150, GroupLayout.PREFERRED_SIZE)
										.addGap(25)
										.addComponent(button, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE))
									.addGroup(Alignment.LEADING, gl_panel_3.createSequentialGroup()
										.addComponent(TestingDataLoadButton, GroupLayout.PREFERRED_SIZE, 116, GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(ComponentPlacement.RELATED)
										.addComponent(testComboBox, GroupLayout.PREFERRED_SIZE, 95, GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(ComponentPlacement.RELATED)
										.addComponent(ClearTest, GroupLayout.DEFAULT_SIZE, 93, Short.MAX_VALUE))))
							.addGap(12))
						.addComponent(btnTestingImageEnhancement, GroupLayout.PREFERRED_SIZE, 318, GroupLayout.PREFERRED_SIZE))
					.addGap(33))
		);
		gl_panel_3.setVerticalGroup(
			gl_panel_3.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_3.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_panel_3.createParallelGroup(Alignment.BASELINE)
						.addComponent(learnDataPathLabel)
						.addComponent(learnTextField, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)
						.addComponent(btnNewButton))
					.addGap(7)
					.addGroup(gl_panel_3.createParallelGroup(Alignment.BASELINE)
						.addComponent(LearningDataLoadButton)
						.addComponent(learninComboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(clearLearn))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(learnImageInhancmentButton)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(gl_panel_3.createParallelGroup(Alignment.BASELINE)
						.addComponent(testTextField, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblTestingDataPath)
						.addComponent(button, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE))
					.addGap(11)
					.addGroup(gl_panel_3.createParallelGroup(Alignment.BASELINE)
						.addComponent(TestingDataLoadButton)
						.addComponent(testComboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(ClearTest))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(btnTestingImageEnhancement)
					.addGap(21))
		);
		LearnPreviewpanel.setLayout(gl_panel_3);
		panel.setLayout(gl_panel);
		
		

		
		
		
	}
}
